package steampunk;

import java.util.List;

import steampunk.entities.Entity;

public class MainEngine {

	private GameVars vars = GameVars.getInstance();
	private CollisionEngine collisions = CollisionEngine.getInstance();
	
	private Thread engineThread = null;
	private final Object playLock = new Object();
	private boolean paused = false;
	
	public synchronized void start() {
		if (engineThread == null) {
			engineThread = new Thread(new MainLoop());
			engineThread.start();
		}
	}
	
	public void play() {
		paused = false;
		synchronized (playLock) {
			playLock.notify();
		}
	}
	
	public void pause() {
		paused = true;
	}
	
	class MainLoop implements Runnable {
		public void run() {
			long msstart = 0;
			long mspass = 0;
			long msend = 0;
			boolean first = true;
			double secs = 0;
			
			while (true) {
				msend = System.currentTimeMillis();
				mspass = msend - msstart;
				msstart = System.currentTimeMillis();
				if (first) {
					first = false;
					mspass = 0;
				}
				secs = mspass / 1000.;
				
				while (paused) {
					synchronized (playLock) {
						try {
							playLock.wait();
						} catch (InterruptedException e) {
							
						}
					}
					
					// make sure the time stays functional
					msstart = System.currentTimeMillis();
					mspass = 0;
					secs = 0;
				}
				
				synchronized (vars.elock) {
					List<Entity> all = vars.getAllEntities();
					for (Entity ent : all) {
						ent.update(secs);
					}
				}
				
				collisions.detectCollisions();
			}
		}
	}
}
